<template>
  <div>
    <a-form-model class="user-layout-login" @keyup.enter.native="handleSubmit">
      <div v-if="customActiveKey === 'tab1'">
        <a-tabs
          :activeKey="customActiveKey"
          :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
          @change="handleTabClick"
          defaultActiveKey="1"
        >
          <a-tab-pane key="tab1" tab="账号密码">
            <login-account
              ref="alogin"
              @validateFail="validateFail"
              @success="requestSuccess"
              @fail="requestFailed"
            ></login-account>
          </a-tab-pane>

          <!-- <a-tab-pane key="tab2" tab="手机号登录">
          <login-phone ref="plogin" @validateFail="validateFail" @success="requestSuccess" @fail="requestFailed"></login-phone>
        </a-tab-pane> -->
        </a-tabs>

        <a-form-model-item>
          <a-checkbox @change="handleRememberMeChange" default-checked>自动登录</a-checkbox>
          <router-link :to="{ name: 'alteration' }" class="forge-password" style="float: right"> 忘记密码 </router-link>
          <router-link :to="{ name: 'register' }" class="forge-password" style="float: right; margin-right: 10px">
            注册账户
          </router-link>

          <div class="pcHost">
            <div class="u-divider">
              <div class="u-divider-line"></div>
              <div class="u-divider-text">快捷登录</div>
              <div class="u-divider-line"></div>
            </div>
            <div class="u-divider">
              <img src="../../assets/chat/wxlogo.png" class="wxKuaJie" @click="goNavTab('scanCode')" alt="" />
              <img src="../../assets/chat/modie.png" @click="chanPhone" alt="" />
            </div>
          </div>
        </a-form-model-item>
      </div>
      <a-form-model-item v-else>
        <login-phone
          ref="plogin"
          @validateFail="validateFail"
          @success="requestSuccess"
          @fail="requestFailed"
          @chanPhone="chanPhone"
        ></login-phone>
      </a-form-model-item>
      <div class="disclaimer">
        <div class="">
          <el-checkbox v-model="claimerIcon">已阅读并同意</el-checkbox>
        </div>
        <router-link
          :to="{ path: '/DiscLaimer', query: { type: '1' } }"
          style="float: right; color: #1890ff !important; cursor: pointer"
          >《免责声明》</router-link
        >
        和
        <router-link
          :to="{ path: '/DiscLaimer', query: { type: '2' } }"
          style="float: right; color: #1890ff !important; cursor: pointer"
          >《分销协议》</router-link
        >
      </div>
      <a-form-item class="wxMargin">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="loginBtn"
          @click.stop.prevent="handleSubmit"
          :disabled="loginBtn"
          >确定
        </a-button>
      </a-form-item>
      <!-- 手机端登录 -->
      <wx-scan-code ref="wxCodeSelect"></wx-scan-code>
    </a-form-model>
    <two-step-captcha
      v-if="requiredTwoStepCaptcha"
      :visible="stepCaptchaVisible"
      @success="stepCaptchaSuccess"
      @cancel="stepCaptchaCancel"
    ></two-step-captcha>
    <login-select-tenant ref="loginSelect" @success="loginSelectOk"></login-select-tenant>

    <!-- <third-login ref="thirdLogin"></third-login> -->
  </div>
</template>

<script>
import Vue from 'vue'
import { mapActions, mapGetters, mapState } from 'vuex'
import {
  ACCESS_TOKEN,
  USER_NAME,
  USER_INFO,
  ENCRYPTED_STRING,
  UI_CACHE_DB_DICT_DATA,
  ACCESS_CODE,
} from '@/store/mutation-types'
import { welcome } from '@/utils/util'
import ThirdLogin from './third/ThirdLogin'
import WxScanCode from './scanCode/WxScanCode'
import LoginSelectTenant from './LoginSelectTenant'
import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
import { getEncryptedString } from '@/utils/encryption/aesEncrypt'
import { timeFix } from '@/utils/util'

import LoginAccount from './LoginAccount'
import LoginPhone from './LoginPhone'

export default {
  components: {
    LoginSelectTenant,
    TwoStepCaptcha,
    ThirdLogin,
    LoginAccount,
    LoginPhone,
    WxScanCode,
  },
  data() {
    return {
      tem_poll: null,
      scene: '',
      userId: '',
      claimerIcon: false,
      customActiveKey: 'tab1',
      rememberMe: true,
      loginBtn: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      encryptedString: {
        key: '',
        iv: '',
      },
      userResultData: null,
    }
  },
  created() {
    Vue.ls.remove(ACCESS_TOKEN)
    this.getRouterData()
    this.rememberMe = true
  },
  beforeDestroy() {
    //清除定时器
    this.getClearInterval()
  },
  mounted() {
    //轮询监听微信登录
    try {
      this.userId = this.$route.query.userId
      console.log('this.userId', this.userId)
      if (this.userId) {
        this.tem_poll = setInterval(this.loginPoll, 1000)
      }
    } catch {}
    //轮询监听微信登录
  },
  methods: {
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    loginPoll() {
      this.$http
        .post('/wechat/api/wechatOpenIdLogin?sceneStr=' + this.userId)
        .then((res) => {
          this.userResultData = res.result
          console.log('this.userResultData', this.userResultData)
          if (res.success) {
            Vue.ls.set(ACCESS_CODE, res.result.code, 30 * 24 * 60 * 60 * 1000)
            this.userInfoData = res.result.userInfo
            // 清除定时器
            this.getClearInterval()
            this.wxLogin(res.result)

            return
          }
        })
        .catch((error) => {
          console.log('error', error)
        })
    },
    //账号密码登录
    wxLogin(results) {
      localStorage.setItem('username', JSON.stringify(this.userInfoData.username))
      localStorage.setItem('userAll', JSON.stringify(this.userInfoData))
      const result = results
      const userInfo = result.userInfo
      Vue.ls.set(ACCESS_TOKEN, result.token, 30 * 24 * 60 * 60 * 1000)
      Vue.ls.set(USER_NAME, userInfo.username, 30 * 24 * 60 * 60 * 1000)
      Vue.ls.set(USER_INFO, userInfo, 30 * 24 * 60 * 60 * 1000)
      Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 30 * 24 * 60 * 60 * 1000)
      this.$store.commit('SET_TOKEN', result.token)
      this.$store.commit('SET_INFO', userInfo)
      this.$store.commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
      this.$store.commit('SET_AVATAR', userInfo.avatar)
      this.wxLoginSuccess()
      this.$store.dispatch('userLimitList', { userId: this.userInfo().id })
    },
    getClearInterval() {
      clearInterval(this.tem_poll)
      this.tem_poll = null
    },
    goToDisclaimer() {
      let url = process.env.VUE_APP_API_BASE_URL.split('/')
      // let distributionAddress = url[0] + '//' + url[2] + '/' + '?code=' + code
      let distributionAddress = url[0] + '//' + 'localhost:3000' + '/DiscLaimer'
      console.log('this.distributionAddress', distributionAddress)
      window.open(distributionAddress, '_blank')
    },
    handIconChange() {
      console.log('1111111111111111')
      this.claimerIcon = '1'
      if (this.claimerIcon === '1') {
        this.claimerIcon = '0'
      } else {
        this.claimerIcon = '1'
      }
    },
    goNavTab(url) {
      this.$router.push({ name: url })
    },
    chanPhone() {
      if (this.customActiveKey === 'tab1') {
        this.customActiveKey = 'tab2'
      } else {
        this.customActiveKey = 'tab1'
      }
    },
    handleTabClick(key) {
      this.customActiveKey = key
    },
    handleRememberMeChange(e) {
      this.rememberMe = e.target.checked
    },
    /**跳转到登录页面的参数-账号获取*/
    getRouterData() {
      this.$nextTick(() => {
        let temp = this.$route.params.username || this.$route.query.username || ''
        if (temp) {
          this.$refs.alogin.acceptUsername(temp)
        }
      })
    },

    //登录
    handleSubmit() {
      this.loginBtn = true
      if (this.claimerIcon) {
        if (this.customActiveKey === 'tab1') {
          // 使用账户密码登录
          this.$refs.alogin.handleLogin(this.rememberMe)
        } else {
          //手机号码登录
          this.$refs.plogin.handleLogin(this.rememberMe)
        }
      } else {
        this.loginBtn = false
        this.$message.info('请勾选免责声明和分销协议')
      }
    },
    // 校验失败
    validateFail() {
      this.loginBtn = false
    },
    // 登录后台成功
    requestSuccess(loginResult) {
      this.$refs.loginSelect.show(loginResult)
    },
    //登录后台失败
    requestFailed(err) {
      let description = ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试'
      this.$notification['error']({
        message: '登录失败',
        description: description,
        duration: 4,
      })
      //账户密码登录错误后更新验证码
      if (this.customActiveKey === 'tab1' && description.indexOf('密码错误') > 0) {
        this.$refs.alogin.handleChangeCheckCode()
      }
      this.loginBtn = false
    },
    loginSelectOk() {
      this.loginSuccess()
    },
    //登录成功
    loginSuccess() {
      this.$router.push({ path: '/dashboard/analysis' }).catch(() => {
        console.log('登录跳转首页出错,这个错误从哪里来的')
      })
      this.$notification.success({
        message: '欢迎',
        description: `${timeFix()}，欢迎回来`,
      })
    },
    //微信登录成功
    wxLoginSuccess() {
      this.$router.push({ path: '/dashboard/analysis' }).catch(() => {
        console.log('登录跳转首页出错,这个错误从哪里来的')
      })
      this.$notification.success({
        message: '微信登录成功',
        description: `${timeFix()}，欢迎回来`,
      })
    },
    stepCaptchaSuccess() {
      this.loginSuccess()
    },
    stepCaptchaCancel() {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    //获取密码加密规则
    getEncrypte() {
      var encryptedString = Vue.ls.get(ENCRYPTED_STRING)
      if (encryptedString == null) {
        getEncryptedString().then((data) => {
          this.encryptedString = data
        })
      } else {
        this.encryptedString = encryptedString
      }
    },
  },
}
</script>
<style lang="less" scoped>
.main {
  width: 500px;
  // height: 300px;
  padding: 10px;
  border-radius: 20px;
  position: absolute;
  background-color: rgba(255, 255, 255, 0.7);
  top: 150px;
  right: 12%;
}

.user-layout-login {
  label {
    font-size: 14px;
  }
  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
    background: linear-gradient(90deg, #7a6cfc, #f26dbe);
    border: unset;
  }
  button.login-button:hover {
    opacity: 0.7;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}

/deep/.ant-tabs-nav .ant-tabs-tab-active {
  color: white !important;
}
/deep/.ant-tabs-ink-bar {
  background-color: white !important;
}
/deep/.ant-form-item-label > label,
/deep/.ant-checkbox + span,
.user-layout-login .forge-password {
  color: white !important;
}
/deep/.ant-checkbox-checked .ant-checkbox-inner {
  background-color: #7a6cfc !important;
  border-color: #7a6cfc !important;
}
/deep/.ant-tabs-bar {
  display: none !important;
}
.u-divider {
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  .u-divider-line {
    width: 55px;
    height: 1px;
    background: white;
  }
  .u-divider-text {
    margin: 0 10px;
  }
  img {
    margin-right: 10px;
    width: 30px;
    cursor: pointer;
  }
}

.icon {
  text-align: center;
  margin: 0 0 26px 0;
  border-bottom: 2px solid white;
  padding-bottom: 30px;
  position: relative;
}
.pcHost {
  float: left;
  width: 100%;
}

@media screen and (max-width: 767px) {
  .pcHost {
    // display: none;
  }
  .user-layout-login {
    .wxMargin {
      margin-bottom: 10px;
    }
  }
  .wxKuaJie {
    display: none;
  }
}
</style>
<style>
.valid-error .ant-select-selection__placeholder {
  color: #f5222d;
}
</style>